package com.pedro.streamer.fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.os.Environment;
import android.os.Handler;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.google.gson.Gson;
import com.pedro.common.ConnectChecker;
import com.pedro.encoder.input.decoder.AudioDecoderInterface;
import com.pedro.encoder.input.decoder.VideoDecoderInterface;
import com.pedro.encoder.input.gl.render.filters.object.TextObjectFilterRender;
import com.pedro.encoder.utils.gl.TranslateTo;
import com.pedro.library.generic.GenericFromFile;
import com.pedro.library.view.OpenGlView;
import com.pedro.streamer.BmiBaseApp;
import com.pedro.streamer.R;
import com.pedro.streamer.RadioActivity;
import com.pedro.streamer.adapter.AIVideoAdapter;
import com.pedro.streamer.manager.VideoArrManager;
import com.pedro.streamer.utils.FileUtils;
import com.pedro.streamer.utils.RecyclerViewSpacesItemDecoration;
import com.pedro.streamer.utils.SimpleItemTouchHelperCallback;
import com.pedro.streamer.view.FilterSourceView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;


public class AIVideoBlankFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener, ConnectChecker,
        VideoDecoderInterface, AudioDecoderInterface {
    private String TAG = "com.bmi.vcam";
    private int CHOOSE_CODE = 3; // 只在视频库挑选图片的请求码
    private RecyclerView recyclerView;
    private AIVideoAdapter aiVideoAdapter;
    private Context mContext;
    private Boolean isconnected = false;
    private OpenGlView openGlView;

    private ArrayList<Uri> videoPicArr;
    private Uri curVideoPath;
    private TextView btn_start;
    private TextView durText, totalText, volumeText;

    private CheckBox video_volume_switch, videoSwitch;
    private ConstraintLayout constraintLayout, radioSetLayout, videoClipLayout, videoManageLayout, bottomLayout;
    private FilterSourceView filterSourceView;
    private ImageView floatView;

    private int MAX_SELECT_COUNT = 10;

    private Gson gson;

    private SeekBar seekBar, volumeSeekBar;
    private int count = 0;
    private GenericFromFile genericFromFile;
    private VideoArrManager videoArrManager = VideoArrManager.shareInstance();
    private String pushUrl = "rtmp://127.0.0.1:1935/file/live";

    final Handler handler = new Handler();
    final Runnable updateProgress = new Runnable() {
        @Override
        public void run() {
//            int currentPosition = videoView.getCurrentPosition();
//            int maxDuration = videoView.getDuration();
//            if (maxDuration > 0) {
//                seekBar.setProgress(currentPosition);
//                seekBar.setMax(maxDuration);
//            }
//
//
//            durText.setText(convertMillisToDuration(currentPosition));
            handler.postDelayed(this, 100);
        }
    };

    public static String convertMillisToDuration(long millis) {
        long seconds = millis / 1000 % 60;
        long minutes = millis / (1000 * 60) % 60;
        long hours = millis / (1000 * 60 * 60);

        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }


    @Override
    public void onResume() {
        super.onResume();

        videoPicArr = videoArrManager.getVideoArr();
        if (videoPicArr == null) {
            videoPicArr = new ArrayList<>();
        }

        if (recyclerView != null) {
            aiVideoAdapter.setVideoPicArr(videoPicArr);
            aiVideoAdapter.notifyDataSetChanged();
        }


        if (filterSourceView != null) {
            filterSourceView.reloadView();
        }


        if (genericFromFile != null &&  genericFromFile.isStreaming()) {
            genericFromFile.playAudioDevice();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (genericFromFile.isStreaming()) {
            genericFromFile.stopAudioDevice();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
        if (genericFromFile.isStreaming()) {
            genericFromFile.stopStream();
            genericFromFile.stopAudioDevice();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (genericFromFile.isStreaming()) {
            genericFromFile.stopStream();
            genericFromFile.stopAudioDevice();
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        gson = new Gson();
        mContext = BmiBaseApp.getInstance().getApplicationContext();


        recyclerView = view.findViewById(R.id.choose_video_recycle);


        floatView = view.findViewById(R.id.float_view);
        floatView.setOnClickListener(this);

        bottomLayout = view.findViewById(R.id.bottom_manager_layout);

        openGlView = view.findViewById(R.id.surfaceView);
        videoArrManager.setOpenGlView(openGlView);

//        TextObjectFilterRender  textObjectFilterRender = new TextObjectFilterRender();
//        openGlView.addFilter(0,textObjectFilterRender);
//        textObjectFilterRender.setText("这是一个水印", 12f, Color.RED, Color.WHITE);
//        textObjectFilterRender.setPosition(TranslateTo.LEFT);
//        textObjectFilterRender.setAlpha(0.5f);
//        textObjectFilterRender.left2right=true;
//        textObjectFilterRender.period=10f;

        genericFromFile = new GenericFromFile(openGlView, this, this, this);
        genericFromFile.getStreamClient().setReTries(3);//设置重试次数 3次，一般情况下本地除非rtmp端口占用，一般不会连接不上。

        btn_start = (TextView) view.findViewById(R.id.btn_start);
        btn_start.setOnClickListener(this);


        seekBar = view.findViewById(R.id.seek_bar);
        seekBar.setVisibility(View.GONE);

        durText = view.findViewById(R.id.during_time);
        durText.setVisibility(View.GONE);
        totalText = view.findViewById(R.id.total_time);
        totalText.setVisibility(View.GONE);
        constraintLayout = view.findViewById(R.id.bottom_layout);
        constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        seekBar.setOnSeekBarChangeListener(this);


        if (videoPicArr == null) {
            videoPicArr = new ArrayList<>();
        } else if (videoPicArr.size() > 0) {

            curVideoPath = videoPicArr.get(0);

        }

        aiVideoAdapter = new AIVideoAdapter();
        aiVideoAdapter.setVideoPicArr(videoPicArr);
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION, 20);

        recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(stringIntegerHashMap));

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(aiVideoAdapter);

        video_volume_switch = view.findViewById(R.id.video_volume_switch);
        video_volume_switch.setOnCheckedChangeListener(this);
        videoSwitch = view.findViewById(R.id.video_switch);
        videoSwitch.setOnCheckedChangeListener(this);

        radioSetLayout = view.findViewById(R.id.media_set_layout);
        radioSetLayout.setOnClickListener(this);

        volumeSeekBar = view.findViewById(R.id.video_volume_seek_bar);
        volumeSeekBar.setOnSeekBarChangeListener(this);

        volumeText = view.findViewById(R.id.volume_text);

        String volumeStr = FileUtils.getVolume();
        volumeSeekBar.setProgress(Integer.valueOf(volumeStr));
        volumeText.setText(volumeStr);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new SimpleItemTouchHelperCallback(new SimpleItemTouchHelperCallback.ItemTouchHelperAdapter() {
            @Override
            public boolean onItemMove(int fromPosition, int toPosition) {
                if (toPosition < videoPicArr.size()) {
                    if (fromPosition < toPosition) {
                        for (int i = fromPosition; i < toPosition; i++) {
                            Collections.swap(videoPicArr, i, i + 1);
                        }
                    } else {
                        for (int i = fromPosition; i > toPosition; i--) {
                            Collections.swap(videoPicArr, i, i - 1);
                        }
                    }

                    for (int i = 0; i < videoPicArr.size(); i++) {
                        Uri path = videoPicArr.get(i);
                        if (curVideoPath.equals(path)) {
                            Log.d(TAG, "onTextClick: " + i);
                            count = i;
                        }

                    }
                    aiVideoAdapter.notifyItemMoved(fromPosition, toPosition);
                    VideoArrManager.shareInstance().setVideoArr(videoPicArr);

                }

                return false;
            }
        }));
        itemTouchHelper.attachToRecyclerView(recyclerView);


        aiVideoAdapter.setClickListener(new AIVideoAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(Uri videoPath) {


                for (int i = 0; i < videoPicArr.size(); i++) {
                    Uri path = videoPicArr.get(i);
                    if (videoPath.equals(path)) {
                        count = i;
                    }

                }

                if (curVideoPath.equals(videoPicArr.get(count))) {
                    return;
                }

                curVideoPath = videoPicArr.get(count);
                VideoArrManager.shareInstance().setVideoArr(videoPicArr);
                startPlayAndPush();


            }

            @Override
            public void onDeleteClick(Uri videoPath) {
                videoPicArr.remove(videoPath);
                aiVideoAdapter.notifyDataSetChanged();

                VideoArrManager.shareInstance().setVideoArr(videoPicArr);
                if (videoPicArr.size() > 0) {
                    if (curVideoPath.equals(videoPath)) {

                        if (count >= videoPicArr.size()) {
                            count = 0;
                        }
                        curVideoPath = videoPicArr.get(count);
                        startPlayAndPush();
                    } else {
                        for (int i = 0; i < videoPicArr.size(); i++) {
                            Uri path = videoPicArr.get(i);
                            if (videoPath.equals(path)) {
                                count = i;
                            }

                        }


                    }
                } else {
                    if (genericFromFile.isStreaming()) {
                        stopPlayAndPush();
                    }
                }


            }

            @Override
            public void addVideo() {
                if (genericFromFile.isStreaming()) {
                    stopPlayAndPush();
                }
                if (has_permission()) {

                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);     // 创建一个内容获取动作的意图(准备跳到系统视频库)

                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);          // 是否允许多选
                    intent.setType("video/*");         // 类型为视频

                    startActivityForResult(intent, CHOOSE_CODE);   // 打开系统视频库
                } else {
                    request_permission();
                }


            }
        });


        sync_statue_with_files();

        videoClipLayout = view.findViewById(R.id.video_clip);
        videoClipLayout.setOnClickListener(this);
        filterSourceView = view.findViewById(R.id.video_filter_layout);
        videoManageLayout = view.findViewById(R.id.video_manager_layout);

    }

    private Boolean prepare() throws IOException {
        if (curVideoPath == null) return false;
        boolean result1 = genericFromFile.prepareVideo(mContext, curVideoPath);

        boolean result2 = genericFromFile.prepareAudio(mContext, curVideoPath);
        if (result1 || result2) {
            return true;
        } else {
            return false;
        }


    }

    private void startPlayAndPush() {
        try {


            if (genericFromFile.isStreaming()) {
                genericFromFile.stopStream();
            }
            if (genericFromFile.isRecording() || prepare()) {
                if (!genericFromFile.isAudioDeviceEnabled()) {
                    genericFromFile.playAudioDevice();//这不需要播放音频，远端拉流在播放，避免两个播放器都播放音频
                }
                genericFromFile.startStream(pushUrl);
                btn_start.setBackground(mContext.getDrawable(R.mipmap.usb_main_ic_player_pause_n));
            }
        } catch (Exception e) {

        }

    }

    private void stopPlayAndPush() {
    genericFromFile.stopAudioDevice();//这不需要播放音频，远端拉流在播放，避免两个播放器都播放音频
        if (genericFromFile.isStreaming()) {
            genericFromFile.stopStream();
            btn_start.setBackground(mContext.getDrawable(R.mipmap.usb_main_ic_player_play_n));
        }
    }

    private void playFinish() {
        btn_start.setBackground(mContext.getDrawable(R.mipmap.usb_main_ic_player_play_n));
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ai_video_blank, container, false);
    }

    @Override
    public void onClick(View view) {

        int viewID = view.getId();


        if (viewID == R.id.btn_start) {

            if (genericFromFile.isStreaming()) {
                stopPlayAndPush();
            } else {
                startPlayAndPush();
            }

        } else if (viewID == R.id.media_set_layout) {
            if (genericFromFile.isStreaming()) {
                stopPlayAndPush();
            }
            startActivity(new Intent(mContext, RadioActivity.class));
        } else if (viewID == R.id.video_clip) {
            filterSourceView.setVisibility(View.VISIBLE);
        } else if (viewID == R.id.float_view) {
            if (bottomLayout.getVisibility() == View.VISIBLE) {
                bottomLayout.setVisibility(View.GONE);
            } else {
                bottomLayout.setVisibility(View.VISIBLE);
            }

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);


        if (resultCode == RESULT_OK && requestCode == CHOOSE_CODE)  // 从视频库回来
        {

            videoPicArr.clear();
            if (intent.getData() != null)    // 选择一个视频
            {
                Uri uri = intent.getData(); // 获得已选择视频的路径对象
                showVideoFrame(uri); // 显示视频的某帧图片
                curVideoPath = videoPicArr.get(0);
                aiVideoAdapter.setVideoPicArr(videoPicArr);
                aiVideoAdapter.notifyDataSetChanged();
                VideoArrManager.shareInstance().setVideoArr(videoPicArr);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startPlayAndPush();
                    }
                }, 300);


            } else if (intent.getClipData() != null)     // 选择多个视频
            {
                ClipData videos = intent.getClipData(); // 获取剪切板数据


                if (videos.getItemCount() > MAX_SELECT_COUNT) {
                    // 提示用户超出最大选择数
                    Toast.makeText(BmiBaseApp.getInstance().getApplicationContext(), "最多只能选择 " + MAX_SELECT_COUNT + " 个视频", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (videos.getItemCount() > 0)  // 至少选择了一个文件
                {

                    for (int i = 0; i < videos.getItemCount(); i++) {
                        Uri uri = videos.getItemAt(i).getUri();
                        showVideoFrame(uri);
                    }
                    curVideoPath = videoPicArr.get(0);
                    aiVideoAdapter.setVideoPicArr(videoPicArr);
                    aiVideoAdapter.notifyDataSetChanged();
                    VideoArrManager.shareInstance().setVideoArr(videoPicArr);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startPlayAndPush();
                        }
                    }, 300);
                }

            }
        }

    }

    private void showVideoFrame(Uri uri) {
        videoPicArr.add(uri);

    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (!compoundButton.isPressed()) {
            return;
        }


        int id = compoundButton.getId();
        if (id == R.id.video_switch) {
            File disable_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/disable.jpg");
            if (disable_file.exists() == b) {
                if (b) {
                    disable_file.delete();
                } else {
                    try {
                        disable_file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (id == R.id.video_volume_switch) {
            File play_sound_switch = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/no-silent.jpg");
            if (play_sound_switch.exists() != b) {
                if (b) {
                    try {
                        play_sound_switch.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    play_sound_switch.delete();
                }
            }

        }


    }


    private boolean has_permission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED
                    && getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_DENIED;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Toast.makeText(getActivity(), R.string.permission_lack_warn, Toast.LENGTH_SHORT).show();
            } else {
                sync_statue_with_files();

            }
        }

    }

    private void request_permission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                    || getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.permission_lack_warn);
                builder.setMessage(R.string.permission_description);

                builder.setNegativeButton(R.string.negative, (dialogInterface, i) -> Toast.makeText(getActivity(), R.string.permission_lack_warn, Toast.LENGTH_SHORT).show());

                builder.setPositiveButton(R.string.positive, (dialogInterface, i) -> requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1));
                builder.show();
            }
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        if (!seekBar.isPressed()) {
            return;
        }

        int viewID = seekBar.getId();
        if (viewID == R.id.seek_bar) {

        } else if (viewID == R.id.video_volume_seek_bar) {
            volumeText.setText(String.valueOf(seekBar.getProgress()));
        }


    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (!seekBar.isPressed()) {
            return;
        }
        int viewID = seekBar.getId();
        if (viewID == R.id.video_volume_seek_bar) {
            FileUtils.setVolume(String.valueOf(seekBar.getProgress()));
        }


    }


    @Override
    public void onConnectionStarted(@NonNull String url) {


    }

    @Override
    public void onConnectionSuccess() {
        isconnected = true;
        Log.d(TAG, "Connected Success");
    }

    @Override
    public void onConnectionFailed(@NonNull String reason) {
        if (genericFromFile.getStreamClient().reTry(500, reason, null)) {
            Log.d(TAG, "Retry ");
        } else {
            Log.d(TAG, "Connected fail ");
            genericFromFile.stopStream();
            btn_start.setBackground(mContext.getDrawable(R.mipmap.usb_main_ic_player_play_n));

        }

    }

    @Override
    public void onDisconnect() {
        isconnected = false;
        Log.d(TAG, "Connected Disconnect ");
    }

    @Override
    public void onAuthError() {
        genericFromFile.stopStream();
        btn_start.setBackground(mContext.getDrawable(R.mipmap.usb_main_ic_player_play_n));
        Log.d(TAG, "onAuthError ");
    }

    @Override
    public void onAuthSuccess() {
        Log.d(TAG, "onAuthSuccess ");
    }

    @Override
    public void onAudioDecoderFinished() {


    }

    @Override
    public void onVideoDecoderFinished() {
        Log.d(TAG, "onAudioDecoderFinished: ");
        openGlView.post(new Runnable() {
            @Override
            public void run() {
                stopPlayAndPush();
            }
        });

        count++;
        if (count >= videoPicArr.size()) {
            count = 0;
        }
        curVideoPath = videoPicArr.get(count);
        openGlView.post(new Runnable() {
            @Override
            public void run() {
                startPlayAndPush();
            }
        });
    }


    private void sync_statue_with_files() {


        if (!has_permission()) {
            request_permission();
            return;
        }

        File camera_dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1");
        if (!camera_dir.exists()) {
            camera_dir.mkdir();
        }


        File videoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/VideoManager");
        if (!videoFile.exists()) {
            videoFile.mkdir();
        }

        File TextureMapFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/TextureMap");
        if (!TextureMapFile.exists()) {
            TextureMapFile.mkdir();
        }


        File disable_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/disable.jpg");
        videoSwitch.setChecked(!disable_file.exists());

//        File force_show_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/force_show.jpg");
//        force_show_switch.setChecked(force_show_file.exists());

        File play_sound_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/no-silent.jpg");
        video_volume_switch.setChecked(play_sound_file.exists());

        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/flv_url.jpg");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        Log.d(TAG, "sync_statue_with_files: ");
        String volumeStr = FileUtils.getVolume();
        volumeText.setText(volumeStr);
        volumeSeekBar.setProgress(Integer.valueOf(volumeStr));

//        File force_private_dir_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/private_dir.jpg");
//        force_private_dir.setChecked(force_private_dir_file.exists());

//        File disable_toast_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera1/no_toast.jpg");
//        disable_toast_switch.setChecked(disable_toast_file.exists());

    }
}